<?php
declare (strict_types = 1);

namespace app\controller\api\v1\user\expert;

use app\controller\api\ApiController;
use app\model\communal\UserExpertModel;
use app\service\logic\common\maintain\CcService;
use app\service\logic\common\maintain\CqService;
use app\service\logic\common\maintain\CsService;
use app\service\logic\common\order\OrderConsultService;
use app\service\logic\common\user\ExpertEvaluateService;
use app\service\logic\common\user\ExpertFollowService;
use app\service\logic\common\user\ExpertItemService;
use app\service\logic\common\user\ExpertService;
use app\service\logic\common\user\ExpertVisitService;
use app\validate\common\order\ConsultValidate;
use app\validate\common\user\ExpertValidate;
use Carbon\Carbon;
use think\App;
use think\Request;
use think\response\Json;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class ExpertController extends ApiController
{
    protected $service;

    public function __construct(App $app, ExpertService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 专家列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);
        $this->validate($params, ExpertValidate::class . '.index');

        $fun = function ($model) {
            // 评价数量
            $model['eval_number'] = invoke(ExpertEvaluateService::class)->getNumberByExpertId($model['id']);
            return $model;
        };
        $result = $this->service->getList($params, $search_fields, $search, [], $fun);
        return amis($result);
    }

    /**
     * 下拉菜单
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function options(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $drop = $this->service->getOptions($params, $search_fields, $search);
        return amis(['options' => $drop]);
    }

    /**
     * 详情
     *
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function read(Request $request)
    {
        $params = $request->only(['id']);
        $this->validate($params, ExpertValidate::class . '.read');
        $user = $request->middleware('user');

        $fun = function ($model) use ($user) {
            // 培训经历
            $trainingMap = [];
            if (!empty($model['training'])) {
                foreach ($model['training'] as $kk=>$ii) {
                    $trainingExperience = explode(',', $ii['training_experience']);
                    $trainingMap[] = [
                        'training_experience' => [
                            'start' => Carbon::createFromTimestamp($trainingExperience[0])->format('Y-m-d H:i:s'),
                            'end' => Carbon::createFromTimestamp($trainingExperience[1])->format('Y-m-d H:i:s')
                        ],
                        'training_content' => $ii['training_content'],
                    ];
                }
            }
            $model['training_map'] = $trainingMap;

            // 是否被当前用户关注
            $model['is_follow'] = invoke(ExpertFollowService::class)->isFollow($user['id'], $model['id']);
            // 粉丝数量
            $model['fans_number'] = invoke(ExpertFollowService::class)->getFansNumberByExpertId($model['id']);
            // 访客数量
            $model['visit_number'] = invoke(ExpertVisitService::class)->getVisitNumberByExpertId($model['id']);
            // 评价数量
            $model['eval_number'] = invoke(ExpertEvaluateService::class)->getNumberByExpertId($model['id']);
            return $model;
        };
        $result = $this->service->read($params, [], $fun);
        // 增加访问数量
        invoke(ExpertVisitService::class)->create(['user_id' => $user['id'], 'expert_id' => $result['id']]);
        return amis($result);
    }

    /**
     * 筛选-服务类别(擅长服务)
     *
     * @return Json
     */
    public function service()
    {
        $result = invoke(CsService::class)->getOptions([], ['state'], ['state' => 1], 'name', 'name');
        return amis($result);
    }

    /**
     * 排序选项
     *
     * @return Json
     */
    public function order()
    {
        $options = $this->service->amisOptions(UserExpertModel::$orderOptions);
        return amis(['options' => $options]);
    }

    /**
     * 筛选 咨询方式选项
     *
     * @return Json
     */
    public function consult()
    {
        $options = $this->service->amisOptions(UserExpertModel::$consultOptions);
        return amis(['options' => $options]);
    }

    /**
     * 筛选 服务均价选项
     *
     * @return Json
     */
    public function average()
    {
        $options = $this->service->amisOptions(UserExpertModel::$averageOptions, 'name', 'id', '全部');
        return amis(['options' => $options]);
    }

    /**
     * 筛选 年龄选项
     *
     * @return Json
     */
    public function age()
    {
        $options = $this->service->amisOptions(UserExpertModel::$ageOptions, 'name', 'id', '全部');
        return amis(['options' => $options]);
    }

    /**
     * 筛选-资质选择(专业资质)
     *
     * @return Json
     */
    public function qualification()
    {
        $result = invoke(CqService::class)->getOptions(['search' => '全部'], ['state'], ['state' => 1], 'name', 'name');
        return amis($result);
    }

    /**
     * 筛选-擅长人群(擅长人群)
     *
     * @return Json
     */
    public function crowd()
    {
        $result = invoke(CcService::class)->getOptions(['search' => '全部'], ['state'], ['state' => 1], 'name', 'name');
        return amis($result);
    }

    /**
     * 筛选-其他
     *
     * @return Json
     */
    public function others()
    {
        $options = $this->service->amisOptions(UserExpertModel::$othersOptions);
        return amis(['options' => $options]);
    }

    /**
     * 服务项目
     *
     * @return Json
     */
    public function items()
    {
        $params = $this->request->param();
        $this->validate($params, ExpertValidate::class . '.read');

        $expertId = $params['id'];
        unset($params['id']);
        $result = invoke(ExpertItemService::class)->getList(
            $params, ['expert_id', 'state'], ['expert_id' => $expertId, 'state' => 1], [], null, false
        );
        return amis($result);
    }

    /**
     * 预约咨询
     *
     * @return Json
     */
    public function payment()
    {
        $params = $this->request->param();
        $this->validate($params, ConsultValidate::class . '.consulting');
        $user = $this->request->middleware('user');
        $params['user_id'] = $user['id'];

        // 生成订单
        $order = invoke(OrderConsultService::class)->createFromItem($params);
        // 支付订单
        $payment = invoke(OrderConsultService::class)->payment($order);
        // $payment = invoke(OrderConsultService::class)->paymentPage($order); // debug
        return amis([
            'order' => $order,
            'payment' => $payment,
        ]);
    }
}
